<template>
  <el-dialog :title="title" :width="width" :visible.sync="isShowVisible" center :close-on-click-modal="false" :before-close="() => $emit('notRefresh')">
    <el-form label-width="125px" :model="materialData" ref="materialData" :rules="rules" style="min-height:24vw" v-loading="isLoading">
      <el-tabs v-model="activeName">
        <el-tab-pane name="base"> <span slot="label"><i class="el-icon-date"></i> 基本资料</span>
          <el-card>
            <el-row>
              <el-col :span="8">
                <el-form-item label="订单编码:" prop="fnumber">
                  <el-input v-model="materialData.fnumber" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="第三方id:" prop="foid" id="foid" v-if="false">
                  <el-input v-model="materialData.foid" :disabled="isview"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="车间:" prop="ffactoryid" id="ffactoryid">
                  <el-select v-model="materialData.ffactoryid" :disabled="isview">
    <el-option 
    v-for="item in queryFactoryList" 
    :key="item.deptId" 
    :label="item.deptName" 
    :value="item.deptId" />
                        </el-select>
                </el-form-item>
              </el-col>
               <el-col :span="8">
                <el-form-item label="客户:" prop="fcustomerid" id="fcustomerid">
                   <inputSelect v-if="!isLoading" :f7Disable="isview" v-model="materialData.fcustomerid" 
                   :loadShow="materialData.fcustomername" 
                   :f7Param="ownermaterialf7Param" title="客户列表"
                    @onF7DaTaSelected="onF7MaterialSelected" >
                    </inputSelect>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
             
              <el-col :span="8">
                <el-form-item label="生产类型:" prop="ftype" id="ftype">
                  <tie-enum v-if="!isLoading" v-model="materialData.ftype" className="cn.hxlc.tie.demo.core.enums.ProductionEnum" :disabled="isview"></tie-enum>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
               <el-col>
                <el-form-item label="备注:" prop="fdescription" id="fdescription" >
                   <el-input type="textarea" v-model="materialData.fdescription" :disabled="isview"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

<el-row>
  
</el-row>
 <el-divider content-position="left">订单信息</el-divider>
        <el-row>
            <div style="margin-bottom:10px" v-if="!isview">
                <el-button type="primary"  plain size="small" @click="insertField(-1)" >新增</el-button>
                <el-button type="danger"   plain size="small" @click="$refs.xTable1.removeCheckboxRow()" >删除</el-button>
            </div>
        </el-row>
<el-row>
 
 <vxe-table border
                show-overflow
                highlight-hover-row
                stripe
                resizable
                ref="xTable1"
                class="my_table_insert"
                max-height="300"
                :data="materialentrys"
                :auto-resize="true"
                :edit-rules="entryRules"
                :edit-config="entryConfig"
                >
              <vxe-table-column type="checkbox" width="60"></vxe-table-column>
              <vxe-table-column field="flot" title="生产批号" :edit-render="{name: 'input', attrs: {type: 'text'}}" ></vxe-table-column>
              <vxe-table-column field="fparentid" title="表头ID" v-if="false" ></vxe-table-column>
              <vxe-table-column field="fmaterialid" title="产品名称"  :edit-render="{type: 'default'}">
                  <template v-slot:edit="subscope">
                    <inputSelect v-model="subscope.row.fmaterialid" :f7Param="entryMaterialF7Param" 
                    :loadShow="subscope.row.fmaterialname" 
                    :f7Disable="isview"
                    title="产品信息表"
                    @onF7DaTaSelected="onF7entryMaterialSelectChanged"></inputSelect>
                    </template>
                    <template v-slot="{ row }">
                    {{row.fmaterialname}}
                    </template>
              </vxe-table-column>
              <vxe-table-column field="fmaterialmodel" title="产品模型"></vxe-table-column>
              <vxe-table-column field="fmaterialnumber" title="产品编号"></vxe-table-column>
              <vxe-table-column field="funitid" title="计量单位"  :edit-render="{name: '$select', options : unitList}"></vxe-table-column>
              <vxe-table-column field="finstoretype" title="入库方式" :edit-render="{name: 'select', options : instoreList}">
              </vxe-table-column>
              <vxe-table-column field="fqty" title="预计产量" min = "0" :edit-render="{name: 'input', attrs: {type: 'number'}}"></vxe-table-column>
              <vxe-table-column field="fgoodqty" title="合格数量" v-if="view"></vxe-table-column>
              <vxe-table-column field="fbadqty" title="不合格数量" v-if="view"></vxe-table-column>
              <vxe-table-column field="fdoneqty" title="报工数量" v-if="view"></vxe-table-column>
              <vxe-table-column field="freqqty" title="领料数量" v-if="view"></vxe-table-column>
              <vxe-table-column field="finstoreqty" title="入库数量" v-if="view"></vxe-table-column>
              <vxe-table-column field="fplanenddate" title="预计完工时间" :edit-render="{name: '$input', props: {type: 'date'}}"></vxe-table-column>
</vxe-table>
</el-row>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="!isview" type="primary" @click="saveMaterial">保存</el-button>
      <el-button v-if="!isview" @click="$emit('notRefresh')">取消</el-button>
      <el-button v-if="isview" @click="$emit('notRefresh')">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import xuWorkOrderApi from "@/api/xuSimpleWork/WorkOrderApi"
import UnitApi from '@/api/basedata/UnitApi'
import HttpHandler from "@/handler/HttpHandler";
export default {
  name: 'workOrder_add',
  props: {
    width: { type: String, default: '100vw' },
    fid: { type: Number, },
    fgroupid: { type: Number },
    isview: false,
    operation: { type: String }
  },
  data () {
   
    return {
        view:false,
        fnumberAnable: true,
        flotAnable: true,
        title: '创建订单',
        isShowVisible: true,
        activeName: 'base',
        unitList : [],
        instoreList: [],
        unitApi : new UnitApi(),
        tieHttp : new HttpHandler(),
        http  :new xuWorkOrderApi() ,
        allList : [],
        materialentrys : [
          {
           fgoodqty: 0 ,
          fbadqty : 0,
          fdoneqty : 0,
          freqqty : 0,
          finstoreqty :0
          }
          ],
          queryFactoryList:[],
      rules: {
        ffactoryid: [{ required: true, message: '车间不能为空！', trigger: 'change' }],
        fcustomerid: [{ required: true, message: '客户不能为空！' }],
        ftype: [{ required: true, message: '生产类型不能为空！', trigger: 'change' }],
       
      },
      ownermaterialf7Param : {
            selectId:'fid',
            selectUrl:'/tie-mdm/customer/queryListPage',
            selectTreeField:['fgroupid'],
            selectTreeUrl:'/tie-mdm/customergroup/queryGroupTree',
            selectShow:{spt:'',field:['fname']},
            column:[
            
            {lable:'客户编码',prop:'fnumber',isFilter:true,filterField:'fnumber'},
            {lable:'客户名称',prop:'fname',isFilter:true,filterField:'fname'},
            {lable:'客户类型',prop:'fstatus',isFilter:false,filterField:'fmodel'},
            {lable:'客户简称',prop:'fsimplename',isFilter:true,filterField:'fsimplename'}],
        },
    entryMaterialF7Param :{
            selectId:'fid',
            selectUrl:'/tie-mdm/material/queryListPage',
            selectTreeField:['fgroupid'],
            selectTreeUrl:'/tie-mdm/materialGroup/queryGroupTree',
            selectShow:{spt:'',field:['fname']},
            column:[
           
            {lable:'编号',prop:'fnumber',isFilter:true,filterField:'fnumber'},
            {lable:'名称',prop:'fname',isFilter:false,filterField:'fname'}
            ,{lable:'规格型号',prop:'fmodel',isFilter:false,filterField:'fmodel'}
            ,{lable:'简称',prop:'fsimplename',isFilter:true,filterField:'fsimplename'}
            ],
            defaultFilter:[{field:'fstatus',value:"USED"}]
        },
    entryRules: {
          flot: [{required: true, message: '产品批号不能为空!',trigger:'blur'}],
          fmaterialid: [{required: true, message: '产品类型不能为空！',trigger:'blur' }],
          funitid: [{required: true, message: '计量单位不能为空！',trigger:'blur' }],
          fplanenddate: [{required: true, message: '入库方式不能为空！',trigger:'blur' }],
          fqty: [{required: true, message: '预计产量不能为空',trigger:'blur' }],
          fplanenddate: [{required: true, message: '预计完工时间不能为空'}],
          finstoretype: [{ required: true, message: '入库类型不能为空！', trigger: 'change' }],
        },
        entryConfig:{trigger: 'click', mode: 'cell'},
      materialData: { },
      isLoading: true,
    }
  },
  
  async created () {
  
    let queryFactoryList = await this.http.queryFactoryList({})
    this.queryFactoryList = queryFactoryList.data
    this.isLoading = true
    await this.$NumRuleUtil.getNumber(this, "cn.hxlc.tie.demo.modular.jf.model.result.XjfWorkOrderResult", null, 'materialData', 'fnumberAnable', 'fnumber');
    
   if(this.operation == 'add'){
      }
      else{
          if(this.operation == 'edit'){
              this.title = "编辑订单"
          }else if(this.operation == 'view'){
              this.title = "查看订单";
              this.view = true;
          this.rules = {};
          this.entryConfig = {};
          this.entryRules = {};
          }
          let materialData = await this.http.detail({ fid: this.fid })
          this.materialData = materialData.data
          this.materialentrys = materialData.data.entrys
          
      }
       this.isLoading = false
    this.getUnitList();
    this.getinstoreList();
   
  },
  //  mounted(){
  //   // this.isLoading = true;
  //   // this.isDataLoading = true;
  //     let that = this;
  //     that.$nextTick(function(){
  //       if(!that.$tie.isEmpty(that.materialData.fwarehouseid) && that.materialData.fwarehouseid != 0){
  //         that.$refs.warearea.refresh([{field:'fwarehouseid',value:that.materialData.fwarehouseid}])
  //       }
  //       if(!that.$tie.isEmpty(that.materialData.fwareareaid) && that.materialData.fwareareaid != 0){
  //         that.$refs.location.refresh([{field:'fwareareaid',value : that.materialData.fwareareaid}])
  //       }
  //       that.isLoading = false;
  //       // that.isDataLoading = false;
  //     });
  // },
  methods: {
    async insertField(row){
        let { row: newRow } = await this.$refs.xTable1.insertAt({
          fgoodqty: 0,
          fbadqty : 0,
          fdoneqty : 0,
          freqqty : 0,
          finstoreqty :0
          }, row)
        await this.$refs.xTable1.setActiveCell(newRow, 'fieldName')
      },
    onF7MaterialSelected(row){
        this.materialData.fmaterialname = row.fname;
      },
      onF7entryMaterialSelectChanged(row){
      this.$refs.xTable1.getActiveRecord().row.fmaterialname = row.fname;
      this.$refs.xTable1.getActiveRecord().row.fmaterialid = row.fid;
      this.$refs.xTable1.getActiveRecord().row.fmaterialmodel = row.fmodel;
      this.$refs.xTable1.getActiveRecord().row.fmaterialnumber = row.fnumber;
      },
      getUnitList(){
        this.unitApi.queryList().then(res => {
          let unitList = res.data;
          this.unitList = [];
          for (var i=0;i < unitList.length;i++) {
            this.unitList.push({
                value: unitList[i].fid,
                label: unitList[i].fname,
            })
          }
        })
      },
      getinstoreList(){
          this.http.getEnum({sysName:"tie-demo",className:"cn.hxlc.tie.demo.core.enums.FinstoretypeEnum"}).then(res=>{
            let instoreList = res.data;
            this.instoreList = [];
          for (var i=0;i < instoreList.length;i++) {
            this.instoreList.push({
                value: instoreList[i].code,
                label: instoreList[i].name,
            })
          }
        })
        
      },
    saveMaterial () {
        let materialentrys = this.$refs.xTable1.getTableData().tableData;
        
        let materialData = this.materialData
        if(materialentrys.length == 0){
              this.$tie.showError('','分录不能为空！');
              return;
            }
      this.$refs['materialData'].validate((valid, object) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请耐心等待.....',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          this.materialData.entrys = materialentrys;
          //若有fid证明是编辑没有则是新增
          if (this.fid) {
            materialData.fstatus = 0
            this.http.update(this.materialData).then(res => {
              loading.close()
              this.$tie.showSuccess(res.message)
              this.$emit('close')
            }).catch(e => {
              loading.close()
            })
          } else {
            materialData.fstatus = 0
            //判断分录是否为空
            
           
            this.http.add(this.materialData).then(res => {
              loading.close()
              this.$tie.showSuccess(res.message)
              this.$emit('close')
            }).catch(e => {
              loading.close()
            })
          }
        } else {
          let validArr = []
          Object.keys(object).forEach(function (key) {
            validArr.push(key)
          });
          let validVal = "#" + validArr[0];
          document.querySelector(validVal).scrollIntoView(true);
        }
      })
      
    },
  },
}
</script>

<style >
.vxe-select--panel {
  z-index: 9999 !important;
}

 .vxe-input--panel.type--date, .vxe-input--panel.type--month, .vxe-input--panel.type--week, .vxe-input--panel.type--year {
  z-index: 9998 !important
    }

.col--actived{
  height: 100px !important;

  .vxe-cell{
    height: 100%;

    textarea{
      height: 100%;
    }
  }
}

</style>

